package com.gzcss.gulimall.ware.service.impl;

import com.gzcss.common.constant.WareConstant;
import com.gzcss.gulimall.ware.dao.PurchaseDetailDao;
import com.gzcss.gulimall.ware.entity.PurchaseDetailEntity;
import com.gzcss.gulimall.ware.feign.ProductFeignService;
import com.gzcss.gulimall.ware.service.PurchaseDetailService;
import com.gzcss.gulimall.ware.service.WareSkuService;
import com.gzcss.gulimall.ware.vo.PurchaseDenoVo;
import com.gzcss.gulimall.ware.vo.PurchaseItemDoneVo;
import com.gzcss.gulimall.ware.vo.mergeVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gzcss.common.utils.PageUtils;
import com.gzcss.common.utils.Query;

import com.gzcss.gulimall.ware.dao.PurchaseDao;
import com.gzcss.gulimall.ware.entity.PurchaseEntity;
import com.gzcss.gulimall.ware.service.PurchaseService;
import org.springframework.transaction.annotation.Transactional;


@Service("purchaseService")
public class PurchaseServiceImpl extends ServiceImpl<PurchaseDao, PurchaseEntity> implements PurchaseService {


    @Autowired
    PurchaseDetailService purchaseDetailService;

    @Autowired
    WareSkuService wareSkuService;



    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<PurchaseEntity> page = this.page(
                new Query<PurchaseEntity>().getPage(params),
                new QueryWrapper<PurchaseEntity>()
        );

        return new PageUtils(page);
    }

    /**
     * 查询未分配采购单
     * @param params
     * @return
     */
    @Override
    public PageUtils queryPageunreceivePurchase(Map<String, Object> params) {

        IPage<PurchaseEntity> page = this.page(
                new Query<PurchaseEntity>().getPage(params),
                new QueryWrapper<PurchaseEntity>().eq("status",0).or().eq("status",1)
        );

        return new PageUtils(page);

    }

    @Transactional
    @Override
    public void mergePurchase(mergeVo mergeVo) {
        Long purchaseId = mergeVo.getPurchaseId();
        if(purchaseId == null ){
            //如果采购单不存在，则新增
            PurchaseEntity purchaseEntity = new PurchaseEntity();
            purchaseEntity.setStatus(WareConstant.PurchaseStatusEnum.CREATE.getCode());
            purchaseEntity.setUpdateTime(new Date());
            purchaseEntity.setCreateTime(new Date());
            this.save(purchaseEntity);
            purchaseId = purchaseEntity.getId();
        }

        //TODO 未实现，确认采购单状态0 或者是 1

        List<Long> items = mergeVo.getItems();
        Long finalPurchaseId = purchaseId;
        List<PurchaseDetailEntity> collect = items.stream().map(i -> {
            PurchaseDetailEntity purchaseDetail = new PurchaseDetailEntity();
            purchaseDetail.setId(i);
            purchaseDetail.setPurchaseId(finalPurchaseId);
            //.setStatus(WareConstant.PurchaseDetailStatusEnum.ASSIGNED.getCode());
            return purchaseDetail;
        }).collect(Collectors.toList());

        purchaseDetailService.updateBatchById(collect);

        PurchaseEntity purchaseEntity = new PurchaseEntity();
        purchaseEntity.setId(purchaseId);
        purchaseEntity.setUpdateTime(new Date());
        this.updateById(purchaseEntity);


    }

    @Override
    public void recevied(List<Long> ids) {
        //1、确认当前采购单是新建或者是已分配
        List<PurchaseEntity> collect = ids.stream().map(id -> {
            PurchaseEntity byId = this.getById(id);
            return byId;
        }).filter(item -> {
            if (item.getStatus() == WareConstant.PurchaseStatusEnum.CREATE.getCode() || item.getStatus() == WareConstant.PurchaseStatusEnum.ASSIGNED.getCode()) {
                return true;
            }
            return false;
        }).map(item->{
            item.setStatus(WareConstant.PurchaseStatusEnum.RECEIVE.getCode());
            item.setUpdateTime(new Date());
            return item;
        }).collect(Collectors.toList());
        //2、改变采购单的状态
        this.updateBatchById(collect);
        //3、改变采购项的状态
        collect.forEach(item->{
            //查找采购单对应的采购项
            List<PurchaseDetailEntity> entityList = purchaseDetailService.listDetailByPurchaseId(item.getId());
            //返回对应的采购项目后，改变采购状态
            List<PurchaseDetailEntity> purchaseDetailEntities = entityList.stream().map(id -> {
                PurchaseDetailEntity purchaseDetail = new PurchaseDetailEntity();
                purchaseDetail.setId(id.getId());
                purchaseDetail.setStatus(WareConstant.PurchaseDetailStatusEnum.RECEIVE.getCode());
                return purchaseDetail;
            }).collect(Collectors.toList());
            purchaseDetailService.updateBatchById(purchaseDetailEntities);

        });
    }

    @Transactional
    @Override
    public void done(PurchaseDenoVo purchaseDenoVo) {

        Long id = purchaseDenoVo.getId();

        //1、改变采购项状态
        Boolean flag = true;
        List<PurchaseItemDoneVo> items = purchaseDenoVo.getItems();
        List<PurchaseDetailEntity> updateId = new ArrayList<>();

        for (PurchaseItemDoneVo item: items) {
            PurchaseDetailEntity detailEntity = new PurchaseDetailEntity();
            if(item.getStatus() == WareConstant.PurchaseDetailStatusEnum.HASERROR.getCode()){
                flag = false;
                detailEntity.setStatus(item.getStatus());
            }else{
                //3、将成功的入库
                detailEntity.setStatus(item.getStatus());
                PurchaseDetailEntity entity = purchaseDetailService.getById(item.getItemId());
                wareSkuService.addStock(entity.getSkuId(),entity.getWareId(),entity.getSkuNum());

            }
            detailEntity.setId(item.getItemId());
            updateId.add(detailEntity);
        }
        //更新采购项
        purchaseDetailService.updateBatchById(updateId);

        //2、改变采购单状态
        PurchaseEntity purchaseEntity = new PurchaseEntity();
        purchaseEntity.setId(id);
        purchaseEntity.setUpdateTime(new Date());
        purchaseEntity.setStatus(flag?WareConstant.PurchaseStatusEnum.FINISH.getCode():WareConstant.PurchaseStatusEnum.HASERROR.getCode());
        this.updateById(purchaseEntity);


    }

}
